<?php

namespace yisyus\supply\utils;

/**
 * AES加解密工具
 */
class AES
{
    /**
     * 加密字符串
     * @param string $data 字符串
     * @param string $key 加密key
     * @param string $iv 加密向量
     * @return string
     */
    public static function encrypt(string $data, string $iv, string $key): string
    {
        $encrypted = openssl_encrypt($data, "AES-128-CBC", $key, true, $iv);
        return base64_encode($encrypted);
    }

    /**
     * 解密字符串
     * @param string $data 字符串
     * @param string $key 加密key
     * @param string $iv 加密向量
     * @return array|string
     */
    public static function decrypt(string $data, string $iv, string $key)
    {
        $decrypted = openssl_decrypt(base64_decode($data), 'AES-128-CBC', $key, true, $iv);
        $json_str = rtrim($decrypted, "\0");
        if (empty($json_str)) throw new AESException('无效的加密字符串', 400);
        $rst = json_decode($json_str, true);
        return $rst ?? $json_str;
    }


}